package c_008;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * reentrantlock用于替代synchronized
 * 由于m1锁定this,只有m1执行完毕m2才能执行
 *
 * 使用reentrantlock可以完成同样的功能
 * 需要注意的是,必须要手动释放锁
 * 使用syn锁的话如果遇到异常,jvm会自动释放锁,但是lock必须得手动释放
 */
public class T02_ReentrantLock1 {

    Lock lock = new ReentrantLock();    //可以替代synchronized

    void m1(){
        try{
            lock.lock();    //synchronized(this)
            for(int i = 0; i < 10; i++){
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (Exception e){

        } finally {
            lock.unlock();
        }
    }

    void m2(){
        try{
            lock.lock();
            System.out.println("m2...");
        }finally {
            lock.unlock();

        }
    }

    public static void main(String[] args) {
        T02_ReentrantLock1 rl = new T02_ReentrantLock1();
        new Thread(rl::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(rl::m2).start();
    }

}
